package controllers;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import models.JSONReqException;
import models.Menu;
import models.Result;
import models.User;

import org.apache.commons.lang.StringUtils;
import org.h2.result.ResultRemote;
import org.tempuri.InJsonData;
import org.tempuri.ReturnResult;
import org.tempuri.WebServiceHelpUtil;

import play.Play;
import play.cache.Cache;
import play.data.Upload;
import play.libs.Files;
import play.mvc.Controller;
import play.mvc.Http.Header;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;

import config.AppConfig;
import config.SessionConfig;
import utils.HelpUtils;

public class CommonController extends BaseController{
	
	private static String[] allowFiles = { ".rar", ".doc", ".docx", ".zip", ".pdf",".txt", ".gif", ".png", ".jpg", ".jpeg", ".bmp", ".xls",".xlsx" };
	
	//上传文件
	public static void uploadAttachments(String dirname, File file){
		User user = getLoginUser();
		dirname = user.getDbName();
		JSONObject json = new JSONObject();
		String fileName = file.getName();
		String[] exts = new String[]{"PDF", "TXT", "PNG", "BMP", "GIF", "XLS", "DOCX", "XLSX", "RAR", "ZIP", "7Z", "JPG", "JPEG", "DOC"};
		List<String> list = Arrays.asList(exts);
		String fileExtName = fileName.substring(fileName.lastIndexOf('.')+1, fileName.length());
		if(!list.contains(fileExtName.toUpperCase())){
			json.put("success", false);
			json.put("errorMsg", "未知文件类型");
			renderJSON(json);
			return;
		}
		String uuid = UUID.randomUUID().toString();
		String newFileName = uuid + "." + fileExtName;
		json.put("AttachmentGuid", uuid);
		json.put("FileName", fileName.substring(0, fileName.lastIndexOf('.')));
		String filePath = "public/upload/"+dirname+ "/" + newFileName;
		json.put("FilePath", filePath);
		json.put("Extension", fileExtName);
		json.put("FileWithExtension", fileName);
		json.put("isNew", true);
		SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		json.put("UpdateTime", time.format(new Date()));
		Files.copy(file, Play.getFile(filePath));
		json.put("success", true);
		renderJSON(json);
	}

	/**
	 * 上传文件
	 * @param file
	 */
	public static void uploadAttachments(File file){
		JSONObject json = new JSONObject();
		String fileName = file.getName();
		String fileExtName = getFileExt(fileName);
		if(!checkFileType(fileName)){
			json.put("success", false);
			json.put("errorMsg", "不允许的文件类型");
			renderJSON(json);
			return;
		}
		User user = getLoginUser();
		String  dirname = user.getDbName();
		String uuid = UUID.randomUUID().toString();
		String newFileName = uuid + fileExtName;
		json.put("AttachmentGuid", uuid);
		json.put("FileName", fileName.substring(0, fileName.lastIndexOf('.')));
		String filePath = "public/upload/"  + dirname + "/" + newFileName;
		json.put("FilePath", filePath);
		json.put("Extension", fileExtName);
		json.put("FileWithExtension", fileName);
		json.put("isNew", true);
		SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		json.put("UpdateTime", time.format(new Date()));
		Files.copy(file, Play.getFile(filePath));
		json.put("success", true);
		renderJSON(json);
	}
	
	/**
	 * 上传文件，百度编辑器专用
	 * @param upfile
	 */
	public static void umeUpload(File upfile){
		JSONObject json = new JSONObject();
		String fileName = upfile.getName();
		String fileExtName = getFileExt(fileName);
		if(!checkFileType(fileName)){
			json.put("success", false);
			json.put("errorMsg", "不允许的文件类型");
			renderJSON(json);
			return;
		}
		String uuid = UUID.randomUUID().toString();
		String newFileName = uuid  + fileExtName;
		String filePath = "public/upload/" + newFileName;
		json.put("originalName", fileName);
		json.put("name", fileName);
		json.put("size", upfile.length());
		json.put("type", getFileExt(fileName));
		json.put("url", filePath);
		Files.copy(upfile, Play.getFile(filePath));
		json.put("state", "SUCCESS");
		response.headers.put("Content-Type", new Header("Content-Type","text/html; charset=utf-8"));
		renderJSON(json);
	}
	
	private static boolean checkFileType(String fileName) {
		Iterator<String> type = Arrays.asList(allowFiles).iterator();
		while (type.hasNext()) {
			String ext = type.next();
			if (fileName.toLowerCase().endsWith(ext)) {
				return true;
			}
		}
		return false;
	}
	
	private static String getFileExt(String fileName) {
		return fileName.substring(fileName.lastIndexOf("."));
	}
	
}
